package com.scau.phradmin.business.auth.controller;

import com.google.common.hash.Hashing;
import com.scau.phradmin.business.auth.domain.AuthState;
import com.scau.phradmin.common.domain.ApiResult;
import com.scau.phradmin.common.exceptions.ErrorCode;
import com.scau.phradmin.domain.entity.Admin;
import com.scau.phradmin.domain.mapper.AdminMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.Arrays;

/**
 * 认证相关API
 * @author yuzhiyi
 * @date 2018/8/5 18:38
 */
@RestController
@RequestMapping("/auth/api")
public class AuthApiController {

	Logger logger = LoggerFactory.getLogger(AuthApiController.class);

	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private Environment env;

	/**
	 * 登录API
	 * @param email 邮箱
	 * @param password 密码
	 * @return
	 */
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	public Object login(@RequestParam("email") String email,
						@RequestParam("password") String password,
						HttpServletRequest request){

		Admin admin = adminMapper.getAdminByEmail(email);
		//判断用户是否存在
		if (admin == null){
			logger.debug("email:{} 用户不存在",email);
			ApiResult result = ApiResult.valueOf(false);
			result.setCode(ErrorCode.USER_NOT_REGISTER.getCode());
			return result;
		}
		//判断密码是否正确
		String encryptedPassword = encrypt(password);
		if (!encryptedPassword.equals(admin.getAdminPassword())){
			logger.debug("email:{},password:{} 密码不正确",email,password);
			ApiResult result = ApiResult.valueOf(false);
			result.setCode(ErrorCode.AUTH_PASSWORD_ERROR.getCode());
			return result;
		}
		logger.debug("用户 {} 登录成功",admin.toString());
		//设置Session
		AuthState authState = new AuthState();
		authState.setUserName(admin.getRealName());
		logger.debug("sessionId: "+request.getSession().getId());
		request.getSession().setAttribute(AuthState.getSessionKey(),authState);
		request.getSession().setAttribute("username",admin.getRealName());
		logger.debug("用户{} logined",request.getSession().getAttribute("username"));
		return ApiResult.valueOf(true);
	}

	/**
	 * 原则上不应该暴露管理员申请接口
	 * 因此只有在DEV状态下，该接口才有效
	 */
	@RequestMapping(value = "/register",method = RequestMethod.POST)
	public Object register(@Valid Admin admin){
		if(!isInDev()){
			logger.debug("注册失败，当前不是dev状态");
			return ErrorCode.SERVER_ERROR;
		}
		//判断用户是否已经存在
		if (adminMapper.getAdminByEmail(admin.getEmail())!=null){
			return ErrorCode.AUTH_USER_EXIST;
		}
		//对密码进行加密
		admin.setAdminPassword(encrypt(admin.getAdminPassword()));
		admin.setRegisteredDate(LocalDate.now());
		adminMapper.insert(admin);
		return ApiResult.DEFAULT_SUCCESS_RESULT;
	}

	/**
	 * 判断当前是否是dev状态
	 */
	private boolean isInDev(){
		return Arrays.stream(env.getActiveProfiles()).anyMatch(profiles->profiles.contains("dev"));
	}


	//加密盐
	private static final String SALT = "d78acuncjkad88cj89aw34pda&dhcuioa@;89q2noc";

	//加密算法
	private String encrypt(String input) {
		input = SALT + input + SALT;
		return Hashing.sha256().hashBytes(input.getBytes()).toString();
	}

}
